﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.IO;
using System.Windows.Forms;
using System.Diagnostics;

namespace fap
{
    /// <summary>
    /// INI文件操作专用类
    /// </summary>
    public class IniFile
    {
        #region API声明
        /// <summary>  
        /// 获取所有段落名称
        /// </summary>  
        /// <param name="lpszReturnBuffer">存放段落名称的内存地址,每个段落之间用\0分隔</param>  
        /// <param name="nSize">内存大小(characters)</param>  
        /// <param name="lpFileName">Ini文件</param>  
        /// <returns>内容的实际长度,为0表示没有内容,为nSize-2表示内存大小不够</returns>  
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        private static extern uint GetPrivateProfileSectionNames(
            IntPtr lpszReturnBuffer,
            uint nSize,
            string lpFileName
        );
        /// <summary>  
        /// 获取某个指定段落中所有KEY和Value  
        /// </summary>  
        /// <param name="lpAppName">段落名称</param>  
        /// <param name="lpReturnedString">返回值的内存地址,每个之间用\0分隔</param>  
        /// <param name="nSize">内存大小(characters)</param>  
        /// <param name="lpFileName">Ini文件</param>  
        /// <returns>内容的实际长度,为0表示没有内容,为nSize-2表示内存大小不够</returns>  
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        private static extern uint GetPrivateProfileSection(
            string lpAppName,
            IntPtr lpReturnedString,
            uint nSize,
            string lpFileName
        );
        /// <summary>  
        /// 读取INI文件中指定的Key的值  
        /// </summary>  
        /// <param name="lpAppName">段落名称。如果为null,则读取INI中所有段落名称,每个节点名称之间用\0分隔</param>  
        /// <param name="lpKeyName">Key名称。如果为null,则读取INI中指定段落中的所有KEY,每个KEY之间用\0分隔</param>  
        /// <param name="lpDefault">读取失败时的默认值</param>  
        /// <param name="lpReturnedString">读取的内容缓冲区，读取之后，多余的地方使用\0填充</param>  
        /// <param name="nSize">内容缓冲区的长度</param>  
        /// <param name="lpFileName">INI文件名</param>  
        /// <returns>实际读取到的长度</returns>  
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        private static extern uint GetPrivateProfileString(
            string lpAppName,
            string lpKeyName,
            string lpDefault,
            [In, Out] char[] lpReturnedString,
            uint nSize,
            string lpFileName
        );
        //另一种声明方式,使用 StringBuilder 作为缓冲区类型的缺点是不能接受\0字符，会将\0及其后的字符截断,  
        //所以对于lpAppName或lpKeyName为null的情况就不适用  
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        private static extern uint GetPrivateProfileString(
            string lpAppName,
            string lpKeyName,
            string lpDefault,
            StringBuilder lpReturnedString,
            uint nSize,
            string lpFileName
        );
        //再一种声明，使用string作为缓冲区的类型同char[]  
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        private static extern uint GetPrivateProfileString(
            string lpAppName,
            string lpKeyName,
            string lpDefault,
            string lpReturnedString,
            uint nSize,
            string lpFileName
        );
        /// <summary>  
        /// 将指定的键值对写到指定的段落，如果已经存在则替换。  
        /// </summary>  
        /// <param name="lpAppName">段落，如果不存在此段落，则创建此段落</param>  
        /// <param name="lpString">Item键值对，多个用\0分隔,形如key1=value1\0key2=value2  
        /// <para>如果为string.Empty，则删除指定段落下的所有内容，保留段落</para>  
        /// <para>如果为null，则删除指定段落下的所有内容，并且删除该段落</para>  
        /// </param>  
        /// <param name="lpFileName">INI文件</param>  
        /// <returns>是否成功写入</returns>  
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        [return: MarshalAs(UnmanagedType.Bool)]     //可以没有此行  
        private static extern bool WritePrivateProfileSection(
            string lpAppName,
            string lpString,
            string lpFileName
        );
        /// <summary>  
        /// 将指定的键和值写到指定的段落，如果已经存在则替换  
        /// </summary>  
        /// <param name="lpAppName">段落名称</param>  
        /// <param name="lpKeyName">键名称。如果为null，则删除指定的段落及其所有的项目</param>  
        /// <param name="lpString">值内容。如果为null，则删除指定段落中指定的键。</param>  
        /// <param name="lpFileName">INI文件</param>  
        /// <returns>操作是否成功</returns>  
        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool WritePrivateProfileString(
            string lpAppName,
            string lpKeyName,
            string lpString,
            string lpFileName
        );
        #endregion

        #region 封装

        #region "读取操作"

        /// <summary>  
        /// 读取INI文件中指定INI文件中的所有节点（section）名称 
        /// </summary>  
        /// <param name="iniFile">Ini文件</param>  
        /// <returns>所有段落,没有内容返回string[0]</returns>  
        public static string[] Read_AllSections(string iniFile)
        {
            uint MAX_BUFFER = 32767;    //默认为32767
            string[] sections = new string[0];      //返回值  
            //申请内存  
            IntPtr pReturnedString = Marshal.AllocCoTaskMem((int)MAX_BUFFER * sizeof(char));
            uint bytesReturned = GetPrivateProfileSectionNames(pReturnedString, MAX_BUFFER, iniFile);
            if (bytesReturned != 0)
            {
                //读取指定内存的内容  
                string local = Marshal.PtrToStringAuto(pReturnedString, (int)bytesReturned).ToString();
                //每个段落之间用\0分隔,末尾有一个\0  
                sections = local.Split(new char[] { '\0' }, StringSplitOptions.RemoveEmptyEntries);
            }
            //释放内存  
            Marshal.FreeCoTaskMem(pReturnedString);
            return sections;
        }
        /// <summary>  
        /// 获取INI文件中指定节点（section）中的所有条目(key=value形式)  
        /// </summary>  
        /// <param name="iniFile">Ini文件</param>  
        /// <param name="section">节点名称</param>  
        /// <returns>指定段落中的所有条目,没有内容返回string[0]</returns>  
        public static string[] Read_AllItems(string iniFile, string section)
        {
            //返回值形式为 key=value,例如 Color=Red  
            uint MAX_BUFFER = 32767;    //默认为32767  
            string[] items = new string[0];      //返回值  
            //分配内存  
            IntPtr pReturnedString = Marshal.AllocCoTaskMem((int)MAX_BUFFER * sizeof(char));
            uint bytesReturned = GetPrivateProfileSection(section, pReturnedString, MAX_BUFFER, iniFile);
            if (!(bytesReturned == MAX_BUFFER - 2) || (bytesReturned == 0))
            {
                string returnedString = Marshal.PtrToStringAuto(pReturnedString, (int)bytesReturned);
                items = returnedString.Split(new char[] { '\0' }, StringSplitOptions.RemoveEmptyEntries);
            }
            Marshal.FreeCoTaskMem(pReturnedString);     //释放内存  
            return items;
        }
        /// <summary>  
        /// 获取INI文件中指定节点（section）中的所有条目的Key列表  
        /// </summary>  
        /// <param name="iniFile">Ini文件</param>  
        /// <param name="section">段落名称</param>  
        /// <returns>如果没有内容,反回string[0]</returns>  
        public static string[] Read_AllKeys(string iniFile, string section)
        {
            string[] value = new string[0];
            const int SIZE = 1024 * 10;
            if (string.IsNullOrEmpty(section))
            {
                throw new ArgumentException("必须指定段落名称", "section");
            }
            char[] chars = new char[SIZE];
            uint bytesReturned = GetPrivateProfileString(section, null, null, chars, SIZE, iniFile);
            if (bytesReturned != 0)
            {
                value = new string(chars).Split(new char[] { '\0' }, StringSplitOptions.RemoveEmptyEntries);
            }
            chars = null;
            return value;
        }
        /// <summary>  
        /// 读取INI文件中指定KEY的字符串型值  
        /// </summary>  
        /// <param name="iniFile">Ini文件</param>  
        /// <param name="section">段落名称</param>  
        /// <param name="key">键名称</param>  
        /// <param name="defaultValue">如果没此KEY所使用的默认值</param>  
        /// <returns>读取到的值</returns>  
        public static string Read_Value(string iniFile, string section, string key,  string defaultValue)
        {
            string value = defaultValue;
            const int SIZE = 1024 * 10;
            if (string.IsNullOrEmpty(section))
            {
                throw new ArgumentException("必须指定段落名称", "section");
            }
            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentException("必须指定键名称", "key");
            }
            StringBuilder sb = new StringBuilder(SIZE);
            uint bytesReturned = GetPrivateProfileString(section, key, defaultValue, sb, SIZE, iniFile);
            if (bytesReturned != 0)
            {
                value = sb.ToString();
            }
            sb = null;
            return value;
        }

     

        #endregion

        #region "写入操作"

        /// <summary>  
        /// 在INI文件中，将指定的键值对写到指定的段落，如果已经存在则替换  
        /// </summary>  
        /// <param name="iniFile">INI文件</param>  
        /// <param name="section">段落，如果不存在此段落，则创建此段落</param>  
        /// <param name="items">键值对，多个用\0分隔,形如key1=value1\0key2=value2</param>  
        /// <returns></returns>  
        public static bool Write_Items(string iniFile, string section, string items)
        {
            if (string.IsNullOrEmpty(section))
            {
                throw new ArgumentException("必须指定段落名称", "section");
            }
         
            if (string.IsNullOrEmpty(items))
            {
                throw new ArgumentException("必须指定键值对", "items");
            }
            string filePath = iniFile.Remove(iniFile.LastIndexOf("\\"));
            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }
            return WritePrivateProfileSection(section, items, iniFile);
        }
        /// <summary>  
        /// 在INI文件中，指定段落写入指定的键及值。如果已经存在，则替换。如果没有则创建INI。  
        /// </summary>  
        /// <param name="iniFile">INI文件</param>  
        /// <param name="section">段落</param>  
        /// <param name="key">键</param>  
        /// <param name="value">值</param>  
        /// <returns>操作是否成功</returns>  
        public static bool Write_Value(string iniFile, string section, string key, string value)
        {
         
            if (string.IsNullOrEmpty(section))
            {
                throw new ArgumentException("必须指定段落名称", "section");
            }
            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentException("必须指定键名称", "key");
            }
            if (value == null)
            {
                throw new ArgumentException("值不能为null", "value");
            }
            string filePath = iniFile.Remove(iniFile.LastIndexOf("\\"));
            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }
            return WritePrivateProfileString(section, key, value, iniFile);
        }

        #endregion

        #region "删除操作"

        /// <summary>  
        /// 在INI文件中，删除指定段落中的指定的键。  
        /// </summary>  
        /// <param name="iniFile">INI文件</param>  
        /// <param name="section">段落</param>  
        /// <param name="key">键</param>  
        /// <returns>操作是否成功</returns>  
        public static bool Delete_Key(string iniFile, string section, string key)
        {
            if (string.IsNullOrEmpty(section))
            {
                throw new ArgumentException("必须指定段落名称", "section");
            }

            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentException("必须指定键名称", "key");
            }
            return WritePrivateProfileString(section, key, null, iniFile);
        }
        /// <summary>  
        /// 在INI文件中，删除指定的段落。  
        /// </summary>  
        /// <param name="iniFile">INI文件</param>  
        /// <param name="section">段落</param>  
        /// <returns>操作是否成功</returns>  
        public static bool Delete_Section(string iniFile, string section)
        {
            if (string.IsNullOrEmpty(section))
            {
                throw new ArgumentException("必须指定段落名称", "section");
            }

            return WritePrivateProfileString(section, null, null, iniFile);
        }
        /// <summary>  
        /// 在INI文件中，删除指定段落中的所有内容。  
        /// </summary>  
        /// <param name="iniFile">INI文件</param>  
        /// <param name="section">段落</param>  
        /// <returns>操作是否成功</returns>  
        public static bool Empty_Section(string iniFile, string section)
        {
            if (string.IsNullOrEmpty(section))
            {
                throw new ArgumentException("必须指定段落名称", "section");
            }
            return WritePrivateProfileSection(section, string.Empty, iniFile);
        }

        #endregion


        #region "其它操作"


        /// <summary>
        /// DataGridViev数据写入INI文件中
        /// </summary>
        /// <param name="dgv">控件</param>
        /// <param name="iniFile">INI文件</param>
        /// <param name="section">节点</param> 
        /// <param name="colStart">开始保存的列,索引0</param>
        /// <param name="colEnd">终止保存的列索引0</param>
        public static void DgvToIni(DataGridView dgv, string iniFile, string section, int colStart, int colEnd)
        {
            string value = "";
            string key = "";
            string str = "|";
            Empty_Section(iniFile, section);

            try
            {
                for (int i = 0; i < dgv.RowCount; i++)// 从零行到控件行数
                {
                    for (int j = colStart; j < colEnd + 1; j++)//从零列到控件列数
                    {
                        if (dgv.Rows[i].Cells[j].Value == null)
                        {
                            dgv.Rows[i].Cells[j].Value = 0;
                        }
                        if (j == colEnd)
                        {
                            str = "";
                        }
                        value = value + dgv.Rows[i].Cells[j].Value.ToString() + str;
                    }
                    key = "Row" + i;
                    Write_Value(iniFile, section, key, value);
                    value = "";
                    str = "|";
                }
            }
            catch { }
        }




        ///// <summary>
        ///// DataGridViev数据写入INI文件中
        ///// </summary>
        ///// <param name="dgv">控件</param>
        ///// <param name="iniFile">INI文件</param>
        ///// <param name="section">节点</param>   
        //public static void DgvToIni(DataGridView dgv, string iniFile, string section)
        //{
        //    string value = "";
        //    string key = "";
        //    string str = ",";
        //    Empty_Section(iniFile, section);

        //    try
        //    {
        //        for (int i = 0; i < dgv.RowCount; i++)// 从零行到控件行数
        //        {
        //            for (int j = 0; j < dgv.ColumnCount; j++)//从零列到控件列数
        //            {
        //                if (dgv.Rows[i].Cells[j].Value == null)
        //                {
        //                    dgv.Rows[i].Cells[j].Value = 0;
        //                }
        //                if (j == dgv.ColumnCount - 1)
        //                {
        //                    str = "";
        //                }
        //                value = value + dgv.Rows[i].Cells[j].Value.ToString() + str;
        //            }
        //            key = "Row" + i;
        //            Write_Value(iniFile, section, key, value);
        //            value = "";
        //            str = ",";
        //        }
        //    }
        //    catch { }

        //}



        /// <summary>
        /// DataGridViev数据写入INI文件中
        /// </summary>
        /// <param name="dgv">控件</param>
        /// <param name="iniFile">INI文件</param>
        /// <param name="section">节点</param>   
        public static void DgvToIni(DataGridView dgv, string iniFile, string section)
        {
           
            string value = "";
            string key = "";
            string str = "|";
            Empty_Section(iniFile, section);
            string Temp = "";

            try
            {
                for (int i = 0; i < dgv.RowCount; i++)// 从零行到控件行数
                {
                    for (int j = 0; j < dgv.ColumnCount; j++)//从零列到控件列数
                    {


                        if (dgv.Rows[i].Cells[j].GetType().Name == "DataGridViewButtonCell")
                        {
                            Temp = "null";
                        }
                        else if (dgv.Rows[i].Cells[j].GetType().Name == "DataGridViewCheckBoxCell")
                        {
                            Temp = (Convert.ToBoolean(dgv.Rows[i].Cells[j].Value)).ToString();

                        }
                        else
                        {
                            if (dgv.Rows[i].Cells[j].Value == null || dgv.Rows[i].Cells[j].Value.ToString() == "")
                            {
                                Temp = " ";
                            }
                            else
                            {
                                Temp = Convert.ToString(dgv.Rows[i].Cells[j].Value);
                            }
                            if (j == dgv.ColumnCount - 1)
                            {
                                str = "";
                            }
                        }


                        value = value + Temp + str;
                    }
                    key = "Row" + i;
                    Write_Value(iniFile, section, key, value);
                    value = "";
                    str = "|";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message+ex.StackTrace);
            }

        }


        ///// <summary>
        ///// 从INI文件中读取DataGridViev数据
        ///// </summary>
        ///// <param name="dgv">控件</param>
        ///// <param name="iniFile">INI文件</param>
        ///// <param name="section">节点</param>   
        //public static bool dgvFromIni(DataGridView dgv, string iniFile, string section)
        //{

        //    dgv.Rows.Clear();//清除数据
        //    string[] str = Read_AllItems(iniFile, section);
        //    if (str.Length == 0)
        //    {
        //        return false;
        //    }
        //    else
        //    {
        //        for (int i = 0; i < str.Length; i++)
        //        {
        //            dgv.Rows.Add();
        //            string strs = Read_Value(iniFile, section, "Row" + i, "");
        //            string[] p = strs.Split(',');
        //            for (int j = 0; j < p.Length; j++)
        //            {
        //                dgv.Rows[i].Cells[j].Value = p[j];

        //            }

        //        }
        //        return true;
        //    }

        //}


        /// <summary>
        /// 从INI文件中读取DataGridViev数据
        /// </summary>
        /// <param name="dgv">控件</param>
        /// <param name="iniFile">INI文件</param>
        /// <param name="section">节点</param>   
        public static void dgvFromIni(DataGridView dgv, string iniFile, string section)
        {
          
            dgv.Rows.Clear();//清除数据
            string[] str = Read_AllItems(iniFile, section);
            try
            {
            if (str.Length == 0)
            {
                return ;
            }
            else
            {
               
                for (int i = 0; i < str.Length; i++)
                {
                    dgv.Rows.Add();
                    string strs = Read_Value(iniFile, section, "Row" + i, "");
                    string[] p = strs.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                    if (p.Length>dgv.ColumnCount)
                    {
                        dgv.Rows.Clear();
                        return;
                    
                    }
                    
                    for (int j = 0; j < p.Length; j++)
                    {


                        if (dgv.Rows[i].Cells[j].GetType().Name == "DataGridViewButtonCell" && p[j] == "null")
                        {
                            dgv.Rows[i].Cells[j].Value = null;
                            continue;
                        }
                        else if (dgv.Rows[i].Cells[j].GetType().Name == "DataGridViewCheckBoxCell")
                        {
                            dgv.Rows[i].Cells[j].Value = Convert.ToBoolean(p[j]);
                            
                            continue;
                        }
                        else if (dgv.Rows[i].Cells[j].GetType().Name == "DataGridViewComboBoxCell")
                        {
                            if (p[j] != " ")
                            {
                                dgv.Rows[i].Cells[j].Value = p[j];
                                continue;
                            }
                            else
                            {
                                dgv.Rows[i].Cells[j].Value = null;
                                continue;
                            }
                        }
                        else
                        {
                            dgv.Rows[i].Cells[j].Value = p[j];
                            continue;
                        }
                    }

                }
               
            }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace);
            }
          
        }
     
        /// <summary>
        /// 从INI文件中读取DataGridViev数据
        /// </summary>
        /// <param name="dgv">控件</param>
        /// <param name="iniFile">INI文件</param>
        /// <param name="section">节点</param>   
        public static void dgvFromIni(DataGridView dgv, string iniFile, string section, int colStart, int colEnd)
        {

            dgv.Rows.Clear();//清除数据
            string[] str = Read_AllItems(iniFile, section);
            try
            {
                if (str.Length == 0)
                {
                    return;
                }
                else
                {

                    for (int i = 0; i < str.Length; i++)
                    {
                        dgv.Rows.Add();
                        string strs = Read_Value(iniFile, section, "Row" + i, "");
                        string[] p = strs.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                        if (p.Length > dgv.ColumnCount)
                        {
                            dgv.Rows.Clear();
                            return;

                        }

                        for (int j = colStart; j < colEnd+1; j++)
                        {


                            if (dgv.Rows[i].Cells[j].GetType().Name == "DataGridViewButtonCell" && p[j] == "null")
                            {
                                dgv.Rows[i].Cells[j].Value = null;
                                continue;
                            }
                            else if (dgv.Rows[i].Cells[j].GetType().Name == "DataGridViewCheckBoxCell")
                            {
                                dgv.Rows[i].Cells[j].Value = Convert.ToBoolean(p[j - colStart]);

                                continue;
                            }
                            else if (dgv.Rows[i].Cells[j].GetType().Name == "DataGridViewComboBoxCell")
                            {
                                if (p[j] != " ")
                                {
                                    dgv.Rows[i].Cells[j].Value = p[j - colStart];
                                    continue;
                                }
                                else
                                {
                                    dgv.Rows[i].Cells[j].Value = null;
                                    continue;
                                }
                            }
                            else
                            {
                                dgv.Rows[i].Cells[j].Value = p[j - colStart];
                                continue;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace);
            }
        }
       
        #endregion





        #endregion
    }
}
